#include <pthread.h>
#include <semaphore.h>
#include <signal.h>

#include "model.h"
#include "utils.h"

#define NUM_WORKER 3
#define TEST_DATA "test_data.txt"

using namespace std;

int main() {
    queue<Client*> client_queue;
    queue<Client*> waiting_clients;

    vector<Client*> clients;
    time_t task_start_time;

    pthread_t workers[NUM_WORKER];
    pthread_t queue_client;
    sem_t sem;
    pthread_mutex_t mutex;

    sem_init(&sem, 0, 0);
    pthread_mutex_init(&mutex, NULL);

    init_client_queue(client_queue, TEST_DATA, clients);
    printf("========================================================================================\n");
    init_worker(workers, NUM_WORKER, waiting_clients, client_queue, &sem, &mutex);

    // Qeueuing clients
    ClientQueueData data;
    data.client_queue = &client_queue;
    data.waiting_queue = &waiting_clients;
    data.mutex = &mutex;
    data.sem = &sem;
    data.start_time = &task_start_time;
    printf("Client ID\tEnter Time\tServe Time\tLeave Time\tEvent\t\n");
    pthread_create(&queue_client, NULL, queueing_client, (void*)&data);

    pthread_join(queue_client, NULL);
    for (int i = 0; i < NUM_WORKER; i++)
        pthread_join(workers[i], NULL);    

    sem_destroy(&sem);
    pthread_mutex_destroy(&mutex);

    // print the final output
    printf("======================================================================================\n");
    for(auto item: clients) {
        item->print_event(task_start_time);
    }
    for (auto item: clients) {
        delete item;
    }

    return 0;
}
